package com.logansoft.zhxypkoa.repository.sys;

import java.util.List;
import java.util.Optional;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;

import com.logansoft.zhxypkoa.domain.sys.Menu;

@RepositoryRestResource(collectionResourceRel = "menus", path = "menus")
public interface MenuRepository extends JpaRepository<Menu, String> {
	@Cacheable(value = "menus", key = "#root.methodName + '-' + #p0 + '-' + #p1") 
	@RestResource(path = "findByParentId")
	public Page<Menu> findByParentId(@Param(value = "parentId") String parentId, Pageable pageable);
	@Cacheable(value = "menus", key = "#root.methodName + '-' + #p0") 
	@RestResource(path = "findByParentIdIsNull")
	public Page<Menu> findByParentIdIsNull(Pageable pageable);
	@Query("select m from Menu m where m.parent.id is null")
	public List<Menu> findTopMenus();
	@Cacheable(value = "menus", key = "#root.methodName + '-' + #p0 + '-' + #p1") 
	@Query(value = "select distinct m from Menu m left join m.roles r left join r.users u, User us where m.parent.id = ?1 and (u.id = ?2 or (us.id = ?2 and us.username = 'admin')) order by m.num asc")
	public List<Menu> getMyMenus(@Param(value = "parentId") String parentId, @Param(value = "userId") String userId);
	@Cacheable(value = "menus", key = "#root.methodName + '-' + #p0") 
	@RestResource(path = "getMyTopMenus")
	@Query(value = "select distinct m from Menu m left join m.roles r left join r.users u, User us where m.parent.id is null and (u.id = ?1 or (us.id = ?1 and us.username = 'admin')) order by m.num asc")
	public List<Menu> getMyMenus(@Param(value = "userId") String userId);
	@Cacheable(value = "menus", key = "#root.methodName + '-' + #p0") 
	@Override
	Page<Menu> findAll(Pageable pageable);
	@CacheEvict(value = "menus", key = "#p0.id", allEntries = true)
	@Override
	<S extends Menu> S save(S entity);
	@Cacheable(value = "menus", key = "#p0") 
	@Override
	Optional<Menu> findById(String id);
	@CacheEvict(value = "menus", key = "#p0", allEntries = true) 
	@Override
	void deleteById(String id);
	@CacheEvict(value = "menus", key = "#p0.id", allEntries = true) 
	@Override
	void delete(Menu entity);
}